<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增时间轴')"/>
    <th:block th:include="include :: summernote-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-timeline-add">
        <input name="mId" type="hidden" th:value="${mId}"/>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">标题：</label>
            <div class="col-sm-8">
                <input name="timeTitle" class="form-control" type="text" required maxlength="25">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">摘要：</label>
            <div class="col-sm-8">
                <textarea name="summary" class="form-control" style="height:100px;" required maxlength="300"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">内容：</label>
            <div class="col-sm-8">
                <input type="hidden" class="form-control" name="content" required>
                <div class="summernote" id="content" required></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">备注：</label>
            <div class="col-sm-8">
                <textarea name="remark" class="form-control"></textarea>
            </div>
        </div>

        <!-- 选择附件 -->
        <div class="form-group">
            <label class="col-sm-3 control-label">附件：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input type="text" class="form-control" id="selectAttachment">
                    <div class="input-group-btn">
                        <button type="button" class="btn btn-white dropdown-toggle" style="height: 31px"
                                data-toggle="dropdown">
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                        </ul>
                    </div>
                    <!-- /btn-group -->
                </div>
            </div>
        </div>

        <!-- 已选择的附件显示 -->
        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-8">
                <div style="overflow-x: auto; width: 100%;">
                    <table id="selectedTable" class="table table-bordered">
                        <thead>
                        <tr>
                            <th style="display: none">id</th>
                            <th>文件</th>
                            <th>大小</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <!-- 选择的数据将会以表格形式展示在这里 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: bootstrap-suggest-js"/>   <!-- 附件选择 -->
<script th:inline="javascript">
    var prefix = "/memorial/TimeLineS"

    // 存储选中的附件数据
    var selectedAttachmentList = [];

    $("#form-timeline-add").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            // 获取所有选中的附件数据
            var attachmentList = selectedAttachmentList;
            // 表单
            var addData = $('#form-timeline-add').serializeArray();
            // 重新组织表单数据
            var formDataObject = {};
            addData.forEach(function (field) {
                formDataObject[field.name] = field.value;
            });
            formDataObject["attachmentList"] = attachmentList;
            $.ajax({
                url: prefix + "/add",
                cache: false,
                data: formDataObject,
                type: 'post',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function (data) {
                    if (data.code == 0) {
                        $.modal.close();
                        var detailUrl = ctx + "memorial/TimeLineM/detail/"+[[${mId}]];
                        $.modal.openTab("时间轴详情", detailUrl,true);
                    } else {
                        $.modal.msgError(data.msg);
                    }
                },
            });

        }
    }

    $(function () {
        $('.summernote').summernote({
            lang: 'zh-CN',
            dialogsInBody: true,
            height: 300,
            callbacks: {
                onChange: function (contents, $edittable) {
                    $("input[name='" + this.id + "']").val(contents);
                },
                onImageUpload: function (files) {
                    var obj = this;
                    var data = new FormData();
                    data.append("file", files[0]);
                    $.ajax({
                        type: "post",
                        url: ctx + "common/upload",
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        dataType: 'json',
                        success: function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $('#' + obj.id).summernote('insertImage', result.url);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                        },
                        error: function (error) {
                            $.modal.alertWarning("图片上传失败。");
                        }
                    });
                }
            }
        });
    });

    // 附件选择
    var attachmentBsSuggest = $("#selectAttachment").bsSuggest({
            indexId: 2,                 // data.value 的第几个数据，作为input输入框的内容
            indexKey: 2,                // data.value 的第几个数据，作为input输入框的内容
            allowNoKeyword: false,      // 是否允许无关键字时请求数据
            hideOnSelect: false,        // 鼠标从列表单击选择了值时，是否隐藏选择列表
            multiWord: true,            // 以分隔符号分割的多关键字支持
            separator: ",",             // 多关键字支持时的分隔符，默认为空格
            getDataMethod: "url",       // 获取数据的方式，总是从 URL 获取
            showHeader: true,           // 是否显示title
            emptyTip:"暂无数据",          // 查询为空时显示的内容，可为 html
            effectiveFieldsAlias: {
                attachmentIndex: "序号",
                attachmentId: "附件id",
                attachmentName: "文件名",
                attachmentSize: "大小"
            },
            /*优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数*/
            url: '/cloud/file/searchLikeFile?searchKey=',
            processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数

                var i, len, data = {
                    value: []
                };

                // 检查返回的JSON数据是否有效
                if (!json || !json.rows || json.rows.length == 0) {
                    return false;
                }

                // 获取建议项的数量
                len = json.rows.length;

                // 提取并返回所需的数据格式
                return {
                    value: json.rows.map(function (item, index) {
                        return {
                            attachmentIndex: index + 1,
                            attachmentId: item.id,
                            attachmentName: item.oldfilename,
                            attachmentSize: item.attachmentSize
                        };
                    })
                };

            }
        })
            .on("onDataRequestSuccess", function (e, result) { // 请求成功的数据

            })
            .on("onSetSelectValue", function (e, keyword, data) { // 选择的数据
                var selectedAttachmentData = `
                    <tr data-id="${data.attachmentId}">
                        <td style="display: none">${data.attachmentId}</td>
                        <td>${data.attachmentName}</td>
                        <td>${data.attachmentSize}</td>
                        <td><button type="button" class="btn delete-btn">删除</button></td>
                    </tr>
                `;
                // 检查表格中是否已经存在具有相同 data-id 的项
                if ($('#selectedTable tbody tr[data-id="' + data.attachmentId + '"]').length === 0) {
                    // 如果不存在，则将数据添加到表格中
                    $('#selectedTable tbody').append(selectedAttachmentData);

                    // 将选择的数据添加到 selectedAttachmentList 数组
                    selectedAttachmentList.push(data);
                } else {
                    // 该数据已存在，跳过添加
                }

            })
            .on("onUnsetSelectValue", function () {
            })
    ;

    // 为每个删除按钮绑定事件
    $('#selectedTable').on('click', '.delete-btn', function () {
        var row = $(this).closest('tr');  // 获取点击的按钮所在的行
        var attachmentId = row.data('id');  // 获取该行的 attachmentId
        // 从 selectedAttachmentList 中删除该数据
        selectedAttachmentList = selectedAttachmentList.filter(function (item) {
            return item.attachmentId !== attachmentId;
        });
        // 删除表格中的该行
        row.remove();
    });



</script>
</body>
</html>